package controller.wechat;

import com.alibaba.fastjson.JSON;
import entity.MenuData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import util.api.ApIURL;
import util.httpclient.HttpService;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by thinkjoy on 2017/8/31.
 * 自定义菜单
 */
public class WeChatDiyMenu implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private HttpService httpService;
    @Autowired
    private WechatQrCode wechatQrCode;

    public void setMenu(){
        try {
            Map<String,Object> value=new HashMap<>();
            List<MenuData> menuDataList=new ArrayList<>();
            List<MenuData> otheritemList=new ArrayList<>();//二级菜单
            MenuData menuData=new MenuData("view","考勤","binding","http://95128.zhits.com.cn:8888");
            MenuData menuData1=new MenuData("view","通知","notice","http://95128.zhits.com.cn:8888");
//            其他（二级）
            MenuData otheritem1=new MenuData("view","我的信息","mymsg","http://95128.zhits.com.cn:8888");
            MenuData otheritem2=new MenuData("view","关于芝麻","about","http://95128.zhits.com.cn:8888");
            MenuData otheritem3=new MenuData("view","二维码","myqr",wechatQrCode.getQrCode());
            otheritemList.add(otheritem1);
            otheritemList.add(otheritem2);
            otheritemList.add(otheritem3);
            MenuData menuData2=new MenuData("其他",otheritemList);

            menuDataList.add(menuData);
            menuDataList.add(menuData1);
            menuDataList.add(menuData2);
            value.put("button",menuDataList);
            String json= JSON.toJSONString(value);
            httpService.doPostAsJson(ApIURL.DIY_MENU_URL+ApIURL.ACCESS_TOKEN,json);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if(contextRefreshedEvent.getApplicationContext().getParent() == null){
            setMenu();
        }
    }
}
